layui.config({
    base: 'assets/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index', //主入口模块
}).use(['index', 'form', 'table', 'laytpl', 'laydate'], function(){
    var $ = layui.$,
        form = layui.form,
        table = layui.table,
        laydate = layui.laydate;

    var userSearchData, curr = 1, limit = 50, field = 'createTime', type = 'desc';
    var userCommonData = JSON.parse(sessionStorage.getItem("userCommonData"));
    sessionStorage.removeItem("userCommonData");
    if(userCommonData != null && !$.isEmptyObject(userCommonData)){
        curr = userCommonData.page;
        limit = userCommonData.limit;
        field = userCommonData.field;
        type = userCommonData.type;
    }

    laydate.render({
        elem: '#time', //指定元素
        type: 'datetime',
        range: true
    });

    table.render({
        id: 'data-table',
        elem: '#data-table',
        url: 'user/list',
        where: getData(),
        toolbar: '#data-table-toolbar',
        title: '用户列表',
        height: globalHeight,
        page: true,
        limit: limit,
        cols: [[
            {field: 'id', title: 'ID', width: 100, align: 'center'},
            {field: 'name', title: '昵称', align: 'center'},
            {field: 'phone', title: '手机号', width: 130, align: 'center'},
            {field: 'icon', title: '头像', width: 80, align: 'center', templet: '#iconTpl'},
            {field: 'gender', title: '性别', width: 60, align: 'center', templet: '#genderTpl'},
            {field: 'host', title: '身份', width: 80, align: 'center', templet: '#hostTpl'},
            {field: 'inviteCount', title: '邀请人数', width: 105, align: 'center', sort: true, templet: '#inviteCountTpl'},
            {field: 'coin', title: '金币(可用/总数)', width: 150, align: 'center', templet: '#coinTpl'},
            {field: 'credit', title: '积分(可用/总数)', width: 150, align: 'center', templet: '#creditTpl'},
            {field: 'identity', title: '会员', width: 80, align: 'center', templet: '#identityTpl'},
            {field: 'totalRecharge', title: '总充值', width: 100, align: 'center'},
            {field: 'createTime', title: '创建时间', width: 160, align: 'center', sort: true},
            {field: 'updateTime', title: '最后操作时间', width: 160, align: 'center', sort: true},
            {field: 'status', title: '账号状态', width: 100, align: 'center', templet: '#statusTpl'},
            {field: 'op', title: '操作', align: 'center', width: 280, templet: '#data-table-bar'}
        ]],
        initSort: { //默认排序
            field: field,
            type: type
        },
        parseData: function(result){
            return {
                "code": result.code, //解析接口状态
                "msg": result.msg, //解析提示文本
                "count": result.data.total, //解析数据长度
                "data": result.data.users //解析数据列表
            };
        },
        done: function (res, curr, count){
            var c = curr;
            if(c > 1){
                curr = 1;
                table.reload('data-table', {
                    page: {
                        curr : c
                    }
                });
            }
            if(userSearchData != null && !$.isEmptyObject(userSearchData)){
                reloadData(userSearchData);
            }
        }
    });

    //头工具栏事件
    table.on('toolbar(data-table)', function(obj){
        switch(obj.event){
            case 'search':
                var data =  getData();
                table.reload('data-table', {
                    url: 'user/list',
                    where: data,
                    page: {
                        curr: 1
                    }
                });
                reloadData(data);
                break;
        };
    });

    //监听排序事件
    table.on('sort(data-table)', function(obj){
        var field = obj.field;  //当前排序的字段名
        var sort = obj.type;    //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

        var data = getData();
        data.field = field;
        data.sort = sort;

        table.reload('data-table', {
            initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。
            where: data,
            page: {
                curr: 1
            }
        });
        reloadData(data);
    });

    //监听行工具事件
    table.on('tool(data-table)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            layer.open({
                type: 2,
                title: '编辑用户',
                offset: '25%',
                content: 'toEditUser',
                area: ['600px', '550px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#id').val(data.id);   //传值到iframe页面
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();
                        post('user/edit', field, false, function (resultData) {
                            obj.update({
                                name: field.name,
                                phone: field.phone,
                                icon: field.icon,
                                gender: field.gender,
                                persionSign: field.persionSign
                            });
                            layer.close(index); //关闭弹层
                            layer.close(load);
                            layer.msg("更新成功");
                        });
                    });

                    submit.trigger('click');
                },
            });
        }else if(obj.event === 'updateStatus'){
            layer.open({
                type: 2,
                title: '封禁用户',
                offset: '25%',
                content: 'toUpdateStatusManage',
                area: ['600px', '450px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#userId').val(data.id);   //传值到iframe页面
                    $(iframeWindow.document).find('#status').val(data.status);
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();
                        post('user/updateStatus', field, false, function (resultData) {
                            obj.update({
                                status:  obj.data.status == 0 ? 1 : 0,
                                op: obj.data.op + 1
                            });
                            layer.close(index);
                            layer.close(load);
                            layer.msg("操作成功");
                        });
                    });

                    submit.trigger('click');
                },
            });
        }else if(obj.event === 'updAudit'){
            var msg;
            var audit;
            if(data.audit == 0){
                msg = '确定禁用该用户主播认证吗？';
                audit = 1;
            }else{
                msg = '确定启用该用户主播认证吗？';
                audit = 0;
            }
            layer.confirm(msg, {offset: '30%'}, function(index){
                // 加载层
                var load = layerLoad();
                post('user/updAudit', {userId: data.id, audit: audit}, false, function (res) {
                    obj.update({
                        audit: audit,
                        op: data.op +1
                    });
                    layer.close(index);
                    layer.close(load);
                    layer.msg(data.audit == 0 ? '禁用成功' : '启用成功');
                });
            });
        }else if(obj.event === 'disableImei'){
            if(data.imeiReason == null){
                layer.open({
                    type: 2,
                    title: '封禁设备号',
                    offset: '25%',
                    content: 'toDisableImeiManage',
                    area: ['500px', '300px'],
                    btn: ['确定', '取消'],
                    success: function(layero, index){   //弹窗成功后回调
                        var iframeWindow = window['layui-layer-iframe' + index];
                        $(iframeWindow.document).find('#userId').val(data.id);   //传值到iframe页面
                        $(iframeWindow.document).find('#imei').val(data.imei);
                    },
                    yes: function (index, layero) {     //确定按钮回调
                        var iframeWindow = window['layui-layer-iframe'+ index],
                            submit = layero.find('iframe').contents().find("#data-submit");

                        //监听提交
                        iframeWindow.layui.form.on('submit(data-submit)', function(data){
                            var field = data.field; //获取提交的字段
                            // 加载层
                            var load = layerLoad();
                            post('user/disableImei', field, false, function (resultData) {
                                obj.update({
                                    imeiReason:  field.reason,
                                    op: obj.data.op + 1
                                });
                                layer.close(index);
                                layer.close(load);
                                layer.msg("操作成功");
                            });
                        });

                        submit.trigger('click');
                    }
                });
            }else{
                var msg = '此设备因：' + data.imeiReason + '被禁用，确认启用该设备吗？';
                layer.confirm(msg, {offset: '30%'}, function(index){
                    // 加载层
                    var load = layerLoad();
                    post('user/disableImei', {userId: data.id, imei: data.imei}, false, function (res) {
                        obj.update({
                            imeiReason: null,
                            op: data.op +1
                        });
                        layer.close(index);
                        layer.close(load);
                        layer.msg('启用设备成功');
                    });
                });
            }
        }else if(obj.event === 'editInvite'){
            //编辑邀请者
            layer.open({
                type: 2,
                title: '编辑邀请者',
                offset: '20%',
                content: 'toEditInvite',
                area: ['500px', '350px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#userId').val(data.id);   //传值到iframe页面
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();

                        //提交 Ajax 成功后，静态更新表格中的数据
                        post('user/editInvite', field, field, function (res) {
                            layer.close(index);
                            layer.close(load);
                            layer.msg(res.desc);
                        });
                    });

                    submit.trigger('click');
                }
            });
        }else if(obj.event === 'recharge'){
            layer.open({
                type: 2,
                title: '充值',
                offset: '25%',
                content: 'toRecharge',
                area: ['500px', '350px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#id').val(data.id);   //传值到iframe页面
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();
                        post('user/recharge', field, false, function (res) {
                            obj.update({
                                coin: res.wallet.activeCoin,
                                credit: res.wallet.activeCredit
                            });
                            layer.close(index); //关闭弹层
                            layer.close(load);
                            layer.msg("充值成功");
                        });
                    });

                    submit.trigger('click');
                },
            });
        }else if(obj.event === 'info'){
            layer.open({
                type: 2,
                title: '用户详情',
                content: 'toUserInfoManage',
                area: ['90%', '90%'],
                offset: ['5%', '5%'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#id').val(data.id);   //传值到iframe页面
                },
            });

        }else if(obj.event === 'viewInvite'){
            userSearchData = {'keyword': $('#keyword').val(), 'gender': $('#gender').val(), 'host': $('#host').val(),
                'identity': $('#identity').val(), 'status': $('#status').val(), 'createTime': $('#time').val()};
            sessionStorage.setItem("userSearchData", JSON.stringify(userSearchData));
            sessionStorage.setItem("userCommonData", JSON.stringify(getCommonData()));

            window.location.href = '/toInviteManage?hrefUrl=/toUserManage&inviteUserId=' + data.id;
        }
    });

    /**
     * 获取查询数据
     * @returns {{host: jQuery, online: jQuery, keyword: (*|jQuery|Array|string|undefined), status: (*|jQuery|Array|string|undefined)}}
     */
    function getData() {
        var keyword, gender, host, identity, status, time;
        userSearchData = JSON.parse(sessionStorage.getItem("userSearchData"));
        sessionStorage.removeItem("userSearchData");
        if(userSearchData != null && !$.isEmptyObject(userSearchData)){
            keyword = userSearchData.keyword;
            gender = userSearchData.gender;
            host = userSearchData.host;
            identity = userSearchData.identity;
            status = userSearchData.status;
            time = userSearchData.time;
        }else{
            keyword = $('#keyword').val();
            gender = $('#gender').val();
            host = $('#host').val();
            identity = $('#identity').val();
            status = $('#status').val();
            time = $('#time').val();
        }

        return {'keyword': keyword, 'gender': gender, 'host': host, 'identity': identity, 'status': status, 'createTime': time};
    }

    /**
     * 重新渲染数据
     * @param data
     */
    function reloadData(data) {
        $('#keyword').val(data.keyword);
        $('#gender').val(data.gender);
        $('#host').val(data.host);
        $('#identity').val(data.identity);
        $('#status').val(data.status);
        $('#time').val(data.createTime);
        laydate.render({
            elem: '#time', //指定元素
            type: 'datetime',
            range: true
        });
        form.render();
    }
});